package com.smartwork.common.sequence;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public abstract class Sequence {
    
    String sql = "REPLACE INTO %s(stub) VALUES('a')";
    
    String lastId = "SELECT LAST_INSERT_ID() NEXTVALUE";
    
    public abstract String getNextValue(Connection conn) throws SQLException;
    
    protected String execute(Connection conn, String tableName) {
        String seq = "";
        String seq_sql = String.format(sql, tableName);
        Lock lock = new ReentrantLock();  
        lock.lock();  
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn.setAutoCommit(false);
            
            stmt = conn.createStatement();
            
            stmt.executeUpdate(seq_sql);
            
            rs = stmt.executeQuery(lastId);
            
            rs.next();
            
            seq = String.valueOf(rs.getLong("NEXTVALUE"));
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
            }
            e.printStackTrace();
        } finally {  
            try {
                if (conn != null) {
                    conn.close();
                    stmt.close();
                    rs.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
            lock.unlock();
        }
        return seq;
    }
}
